<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>授权</title>
		<link rel="stylesheet" href="../../component/pear/css/pear.css" />
	</head>
	<body class="pear-container">
		<div class="layui-card">
			<div class="layui-card-body" style="display: flex; flex-direction: column; min-height: 100px;">
				<div id="menu-tree-id" style="flex-grow: 1;"></div>
				<div style="display: flex; justify-content: flex-end;">
				<button type="button" class="layui-btn" lay-on="getChecked">授权</button>
				</div>
			</div>
		</div>

		<script src="../../component/layui/layui.js"></script>
		<script src="../../component/pear/pear.js"></script>
		<script>
			layui.use(function(){

				let tree = layui.tree;
				let layer = layui.layer;
				let util = layui.util;
				let $ = layui.$;

				util.event('lay-on', {
					getChecked: function(othis){
						let checkedNodes = tree.getChecked('auth');
						let checkedIds = getSelectedNodeIds(checkedNodes);
						let obj={};
						obj.roleId=roleId;
						obj.menuIds=checkedIds;

						$.ajax({
							type: 'post',
							url: 'http://127.0.0.1:8080/auth',
							data: JSON.stringify(obj),
							contentType: 'application/json',
							dataType: 'json',
							success: function(res){
								if(res.code==0){
									let index = parent.layer.getFrameIndex(window.name);
									parent.layer.close(index);
								}else{
									layer.msg(res.msg);
								}
							}
						});
					}
				});

				// 遍历tree的节点，找出被选中的根节点
				function getSelectedNodeIds(treeData){
					let result=[];
					traverse(treeData);

					function traverse(nodes){
						for(let node of nodes){
							if(node.checked){
								if(node.children && node.children.length>0){
									traverse(node.children);
								}else{
									result.push(node.id);
								}
							}
						}
					}

					return result;
				}				

				let url = window.location.href;
				let roleId = url.split("?")[1].split("=")[1];
				$.getJSON('http://127.0.0.1:8080/getMenuListWithAuth', {roleId: roleId}, function(res){
					if(res.code==0){
						tree.render({
							elem: '#menu-tree-id',
							data: res.data,
							showCheckbox: true,
							onlyIconControl: true,
							id: 'auth'
						});
					}else{
						layer.msg(res.msg);
					}
				});				

			});
		</script>
	</body>
</html>
